/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cmti.skeleton.web.shiro;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

/**
 * 用于处理shiro授权异常
 * 直接返回http status code
 * 
 * @author danny
 */
@ControllerAdvice
public class ShiroUnauthorizedExceptionHandler {
    
    @ExceptionHandler(UnauthorizedException.class)
//    @ResponseStatus(HttpStatus.FORBIDDEN) 用这个注解直接返回状态码，不会再有后续处理
    // 返回空的ModelAndView最后会让Servlet容器去处理
    public ModelAndView handleUnauthorizedException(UnauthorizedException uaEx, HttpServletResponse response) {
        try {
            response.sendError(HttpStatus.FORBIDDEN.value());
        } catch (IOException ex) {
            Logger.getLogger(ShiroUnauthorizedExceptionHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
        return new ModelAndView();
    }
    
}
